<?php


namespace app\api\controller\v16;

use app\api\controller\v2\Auth;
use app\common\lib\Util;
use app\common\model\ArticleCollect;

/**
 * 内容收藏相关
 * Class Collect
 * @version 2.0.0
 * @package app\api\controller\v16
 */
class Collect extends Auth
{
    /**
     * 获取用户内容收藏
     * @throws \Exception
     */
    public function index()
    {
        $data = (new ArticleCollect())->getUserCollectPage($this->user['id'], 2);
        return show(config('code.success'), '获取成功', $data);
    }

    /**
     * 收藏/取消收藏
     * @throws \Exception
     */
    public function save()
    {
        $id = input('id/d', 0);
        $type = input('type/d', 0);//[1=>星文，2=>女神动态，3=>女神专区]
        if (!$id || !$type)
        {
            return show(config('code.error'), '服务异常，请稍后再试');
        }
        //验证是否重复操作
        if (Util::commentCheck($this->user['id'], ['id' => $id, 'type' => $type]))
        {
            return show(config('code.error'), '别心急，等一等');
        }
        $articleCollectModel = new ArticleCollect();
        //获取用户已收藏的数据
        $collectIds = array_keys($articleCollectModel->getUserAllCollectFromCache($this->user['id'], $type));
        if (in_array($id, $collectIds))
        {
            $articleCollectModel->delData($this->user['id'], $type, $id);
            return show(config('code.success'), '取消收藏成功');
        }
        $articleCollectModel->saveData($this->user['id'], $id, $type);
        return show(config('code.success'), '收藏成功');
    }

    /**
     * 批量取消文章收藏
     * @throws \Exception
     */
    public function del()
    {
        $ids = input('ids/s', '');
        //验证是否重复操作
        if (Util::commentCheck($this->user['id'], ['ids' => $ids]))
        {
            return show(config('code.error'), '别心急，等一等');
        }
        $articleCollectModel = new ArticleCollect();
        if ($ids)
        {
            $ids = explode(',', $ids);
        } else
        {
            return show(config('code.error'), '取消收藏失败');
        }
        foreach ($ids as $id)
        {
            $articleCollectModel->delData($this->user['id'], 0, 0, $id);
        }
        return show(config('code.success'), '取消收藏成功');
    }
}
